package com.jrauto.CarAppBackend.service.impl;

/**
 * @author : huiMing
 * Date : 2025年09月11日 14:47
 * @version V1.0
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jrauto.CarAppBackend.entity.ChatRoom;
import com.jrauto.CarAppBackend.entity.dto.ChatRoomDTO;
import com.jrauto.CarAppBackend.mapper.ChatRoomMapper;
import com.jrauto.CarAppBackend.service.ChatRoomService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天室服务实现类
 */
@Service
public class ChatRoomServiceImpl extends ServiceImpl<ChatRoomMapper, ChatRoom> implements ChatRoomService {

    @Resource
    private ChatRoomMapper chatRoomMapper;

    @Override
    public ChatRoom createOrGetChatRoom(Integer buyerId, Integer sellerId, Integer carId) {
        // 先查询是否已存在聊天室（基于商品ID和买家ID的唯一约束）
        QueryWrapper<ChatRoom> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("car_id", carId)
                .eq("buyer_id", buyerId);

        ChatRoom existRoom = getOne(queryWrapper);
        if (existRoom != null) {
            return existRoom;
        }

        // 创建新的聊天室
        ChatRoom chatRoom = new ChatRoom();
        chatRoom.setCarId(carId);
        chatRoom.setBuyerId(buyerId);
        chatRoom.setSellerId(sellerId);
        chatRoom.setStatus(1); // 1-正常
        chatRoom.setBuyerUnreadCount(0);
        chatRoom.setSellerUnreadCount(0);
        chatRoom.setCreatedAt(LocalDateTime.now());
        chatRoom.setUpdatedAt(LocalDateTime.now());

        save(chatRoom);
        return chatRoom;
    }

    @Override
    public ChatRoom getChatRoomById(Integer roomId) {
        return getById(roomId);
    }

    @Override
    public List<ChatRoomDTO> getUserChatRooms(Integer userId) {
        return chatRoomMapper.selectUserChatRooms(userId);
    }

    @Override
    public boolean updateLastMessage(Integer roomId, String content) {
        ChatRoom chatRoom = getById(roomId);
        if (chatRoom == null) {
            return false;
        }
        chatRoom.setLastMessage(content);
        chatRoom.setLastMessageTime(LocalDateTime.now());
        chatRoom.setUpdatedAt(LocalDateTime.now());

        return updateById(chatRoom);
    }

    @Override
    public boolean increaseUnreadCount(Integer roomId, Integer userId) {
        ChatRoom chatRoom = getById(roomId);
        if (chatRoom == null) {
            return false;
        }

        // 判断是买家还是卖家的未读消息数需要增加
        if (chatRoom.getBuyerId().equals(userId)) {
            chatRoom.setBuyerUnreadCount(chatRoom.getBuyerUnreadCount() + 1);
        } else if (chatRoom.getSellerId().equals(userId)) {
            chatRoom.setSellerUnreadCount(chatRoom.getSellerUnreadCount() + 1);
        } else {
            return false; // 用户不属于这个聊天室
        }

        chatRoom.setUpdatedAt(LocalDateTime.now());
        return updateById(chatRoom);
    }

    @Override
    public boolean clearUnreadCount(Integer roomId, Integer userId) {
        ChatRoom chatRoom = getById(roomId);
        if (chatRoom == null) {
            return false;
        }

        // 判断是买家还是卖家的未读消息数需要清零
        if (chatRoom.getBuyerId().equals(userId)) {
            chatRoom.setBuyerUnreadCount(0);
        } else if (chatRoom.getSellerId().equals(userId)) {
            chatRoom.setSellerUnreadCount(0);
        } else {
            return false; // 用户不属于这个聊天室
        }

        chatRoom.setUpdatedAt(LocalDateTime.now());
        return updateById(chatRoom);
    }
}